<template>
<div>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form v-loading="formLoading" :model="dataForm"  :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">

       <el-form-item label="所在田块" prop="farmlandInfoId">
        <el-select 
            style="width:100%"
            v-model="dataForm.farmlandInfoId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键字"
            :remote-method="remoteMethod"
            :loading="handlerListLoading"
            v-loadmore="handlerListLoadMore">
            <el-option
            v-for="item in farmList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
            </el-option>
        </el-select>
    </el-form-item>
   
    <el-form-item label="农作物类型" prop="cropDict">
      <!-- <el-input v-model="dataForm.cropDict" placeholder="农作物"></el-input> -->
      <el-select style="width:100%" v-model="dataForm.cropDict" filterable placeholder="请选择农作物类型">
            <el-option
            v-for="item in cropDictList"
            :key="item.id"
            :label="item.value"
            :value="item.id">
            </el-option>
        </el-select>
    </el-form-item>
   
    <el-form-item label="起始时间" prop="startTime">
      <el-date-picker style="width:100%"
            v-model="dataForm.startTime"
            type="datetime"
            placeholder="起始时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            >
          </el-date-picker>
    </el-form-item>
    <el-form-item label="结束时间" prop="endTime">
        <el-date-picker style="width:100%"
            v-model="dataForm.endTime"
            type="datetime"
            placeholder="结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            >
          </el-date-picker>
    </el-form-item>
     <el-form-item label="投入品" prop="inputThing">
      <el-input type="textarea" :rows="3" v-model="dataForm.inputThing" placeholder="投入品"></el-input>
    </el-form-item>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button  v-loading="formLoading" type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>

</div>
</template>

<script>
import { treeDataTranslate } from '@/utils'
  export default {
    data () {
      return {
        visible: false,
        formLoading: false,
        demoVisible: false,
        dataForm: {
          id: 0,

          farmlandInfoId: '',
          deptId: '',
          parentName:'',
          startTime: '',
          endTime: '',
          cropDict: '',
          inputThing: '',
          createId: '',
          createName: '',
          createTime: '',
          updateId: '',
          updateTime: '',
          updateName: '',
          version: '',
          gcFlag: ''
        },
        dataRule: {
          farmlandInfoId: [
            { required: true, message: '所在不能为空', trigger: 'blur' }
          ],
          startTime: [
            { required: true, message: '起始时间不能为空', trigger: 'blur' }
          ],
          endTime: [
            { required: true, message: '结束时间不能为空', trigger: 'blur' }
          ],
          cropDict: [
            { required: true, message: '农作物类型不能为空', trigger: 'blur' }
          ],
          inputThing: [
            { required: true, message: '投入品不能为空', trigger: 'blur' }
          ],
         
        },
         menuList: [],
         multipleSelection: [],
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        key: '',
        handlerList:[],// 处理人列表
        menuListTreeProps: {
          label: 'name',
          children: 'children'
        },
         handlerListLoading: false,
        farmList:[],// 处理人列表
        hadlerParams:{},// 处理人查询参数
        cropDictList:[],// 农作物列表
      }
    },
    methods: {
       init (id) {

      // 获取农作物字典列表
        this.$http({
          url: this.$http.adornUrl('/sys/dict/select'),
          method: 'get',
          params: this.$http.adornParams({
              "type": "crop_00"
          })
        }).then(({data}) => {
          this.cropDictList = treeDataTranslate(data.list, 'id')
        })

      // 加载田块下拉框
        this.handlerListLoadMore('init')

        this.dataForm.id = id || 0
        this.$http({
          url: this.$http.adornUrl('/sys/dept/list'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {

          this.menuList = treeDataTranslate(data, 'id')
        }).then(() => {
        this.visible = true
        this.formLoading = false
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
           })
          }).then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/buss/bussfarmlandputinto/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                debugger;
                this.dataForm.farmlandInfoId = data.bussFarmlandPutInto.farmlandInfoId
                this.dataForm.deptId = data.bussFarmlandPutInto.deptId
                this.dataForm.startTime = data.bussFarmlandPutInto.startTime
                this.dataForm.endTime = data.bussFarmlandPutInto.endTime
                this.dataForm.cropDict = data.bussFarmlandPutInto.cropDict
                this.dataForm.inputThing = data.bussFarmlandPutInto.inputThing
                this.dataForm.createId = data.bussFarmlandPutInto.createId
                this.dataForm.createName = data.bussFarmlandPutInto.createName
                this.dataForm.createTime = data.bussFarmlandPutInto.createTime
                this.dataForm.updateId = data.bussFarmlandPutInto.updateId
                this.dataForm.updateTime = data.bussFarmlandPutInto.updateTime
                this.dataForm.updateName = data.bussFarmlandPutInto.updateName
                this.dataForm.version = data.bussFarmlandPutInto.version
                this.dataForm.gcFlag = data.bussFarmlandPutInto.gcFlag
                 this.menuListTreeSetCurrentNode();
              }
            })
          }
        })
      },
       changeInput() {
        this.demoVisible = true
         if (this.multipleSelection.length == 0) {
           this.search()
         }
      },
      handleSelectionChange(val) {
        console.log('%c------------ 验证是否每次都调用', 'color:green')
        console.log(val)
        this.multipleSelection = val
        let list = []
        val.forEach(x => {
          list.push(x.id)
        })
        this.dataForm.farmlandInfoIds = list.join(',')
      },
       search() {
        this.$http({
          url: this.$http.adornUrl('/buss/bussfarmlandinfo/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'key': this.key
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
            if (this.multipleSelection.length > 0) {
              this.multipleSelection.forEach(x => {
                data.page.list.forEach((y, index) => {
                    if (x.id == y.id) {
                      this.$refs.multipleTable.toggleRowSelection(this.dataList[index], true)
                    }
                })
              })
            }
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
       // 菜单树选中
      menuListTreeCurrentChangeHandle (data, node) {
      debugger;
        this.dataForm.deptId = data.id
        this.dataForm.parentName = data.name
        //选中时触发田块筛选

      },
      // 菜单树设置当前选中节点
      menuListTreeSetCurrentNode () {

        this.$refs.menuListTree.setCurrentKey(this.dataForm.deptId)
        this.dataForm.parentName = (this.$refs.menuListTree.getCurrentNode() || {})['name']
      },
      // 图标选中
      iconActiveHandle (iconName) {
        this.dataForm.icon = iconName
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid && !this.formLoading) {
            this.formLoading = true
            this.$http({
              url: this.$http.adornUrl(`/buss/bussfarmlandputinto/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'farmlandInfoId': this.dataForm.farmlandInfoId,
                'deptId': this.dataForm.deptId,
                'startTime': this.dataForm.startTime,
                'endTime': this.dataForm.endTime,
                'cropDict': this.dataForm.cropDict,
                'inputThing': this.dataForm.inputThing,
                'createId': this.dataForm.createId,
                'createName': this.dataForm.createName,
                'createTime': this.dataForm.createTime,
                'updateId': this.dataForm.updateId,
                'updateTime': this.dataForm.updateTime,
                'updateName': this.dataForm.updateName,
                'version': this.dataForm.version,
                'gcFlag': this.dataForm.gcFlag
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.formLoading = false
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
       // 这里下拉框查询触发的方法
      remoteMethod(query) {
        this.handlerListLoadMore('query',query)
      },
      // 这里写入滚动加载要触发的方法
      handlerListLoadMore (type,query) {
        this.handlerListLoading = true

        if(type && (type == 'init' || type == 'query')){
            this.hadlerParams.page = 1
            this.farmList = []
        }else if(this.hadlerParams.page){
            if(this.hadlerParams.page>=this.hadlerParams.totalPage){
                this.handlerListLoading = false
                return
            }
            this.hadlerParams.page += 1
        }
        
        var _this = this
        this.$http({
            url: this.$http.adornUrl('/buss/bussfarmlandinfo/list'),
            method: 'get',
            params: this.$http.adornParams({
                "name": query, //搜索参数
                "page": _this.hadlerParams.page || 1, //分页参数
                "limit": _this.hadlerParams.limit || 15, //每次查询15条记录
            })
        }).then(({data}) => {
            _this.handlerListLoading = false
            _this.hadlerParams.totalPage = data.page.totalPage
            _this.farmList = _this.handlerList.concat(data.page.list)
        })
      }
    }
  }
</script>
